import {removeToken} from 'utils/auth'
import {getUserInfo} from 'api/user'

const user = {
  state: {
    userId: 0,
    username: '',
    name: '',
    avatar: require('static/default_avatar.png'),
    permissions: [],
    type: ''
  },

  mutations: {
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_TYPE: (state, type) => {
      state.type = type
    }
  },

  actions: {
    // 获取用户信息
    GetUserInfo({commit}) {
      return getUserInfo().then(response => {
        commit('SET_USERID', response.id)
        commit('SET_USERNAME', response.name)
        commit('SET_NAME', response.profile.name)
        if (response.profile.avatar) {
          commit('SET_AVATAR', response.profile.avatar)
        }
        commit('SET_PERMISSIONS', response.permissions.data)
        commit('SET_TYPE', response.type)
      })
    },
    LogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_PERMISSIONS', [])
        commit('SET_TYPE', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
